#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<cstring>
using namespace std;
using ll = long long;
const int N = 4;
int n, m;
ll f[N] = { 1,1,1,0 };
ll a[N][N] = { {0,1,0,0},
            {1,1,1,0},
            {0,0,1,1},
            {0,0,0,1} };
void mulfa(ll c[N], ll f[N], ll a[][N])
{
    ll temp[N] = { 0 };
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
            temp[i] = (temp[i] + f[j] * a[j][i]) % m;
    }
    memcpy(c, temp, sizeof temp);
}
void mulaa(ll c[][N], ll a[][N], ll b[][N])
{
    ll temp[N][N] = { 0 };
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            for (int k = 0; k < N; k++)
                temp[i][j] = (temp[i][j] + a[i][k] * b[k][j]) % m;
        }
    }
    memcpy(c, temp, sizeof temp);
}
int main()
{
    cin >> n >> m;
    int k = n - 1;
    while (k)
    {
        if (k & 1) mulfa(f, f, a);
        mulaa(a, a, a);
        k >>= 1;
    }
    cout << ((n * f[2] - f[3]) % m + m) % m << endl;
    return 0;
}